package utils;

/**
 * Encrypts and decrypts string.
 *
 * @author Skomakar'n
 */
public class HashMaker
{
    /**
     * Returns an encrypted string.
     *
     * @param value The string to encrypt.
     * @return The encrypted string.
     */
    public static String encrypt(String value)
    {
        value = reverse(value);
        String result = "";
        int number = 1 + (int)Math.ceil(Math.random() * 8);

        for (int i = 0; i < value.length(); i += 2)
        {
            if (i < value.length() - 1)
                result += reverse(value.substring(i,i + 2));
            else
                result += value.charAt(i);
        }

        for (int i = 0; i < result.length(); i ++)
            result = result.substring(0,i) + (char)((int)result.charAt(i) + number) + result.substring(i + 1,result.length());

        result += Integer.toString(number);
        result = reverse(result);

        value = result;
        result = "";

        for (int i = 0; i < value.length(); i += 2)
        {
            if (i < value.length() - 1)
                result += reverse(value.substring(i,i + 2));
            else
                result += value.charAt(i);
        }

        return result;
    }

    /**
     * Decrypts an encryption generated by the class.
     *
     * @param value The hash to decrypt.
     * @return The decrypted hash.
     */
    public static String decrypt(String value)
    {
        String result = "";

        for (int i = 0; i < value.length(); i += 2)
        {
            if (i < value.length() - 1)
                result += reverse(value.substring(i,i + 2));
            else
                result += value.charAt(i);
        }

        result = reverse(result);

        int number = Integer.parseInt(result.substring(result.length() - 1,result.length()));

        result = result.substring(0,result.length() - 1);

        for (int i = 0; i < result.length(); i ++)
            result = result.substring(0,i) + (char)((int)result.charAt(i) - number) + result.substring(i + 1,result.length());

        value = result;
        result = "";

        for (int i = 0; i < value.length(); i += 2)
        {
            if (i < value.length() - 1)
                result += reverse(value.substring(i,i + 2));
            else
                result += value.charAt(i);
        }

        result = reverse(result);

        return result;
    }

    /**
     * Returns a string backwards.
     *
     * @param string The string to modify.
     * @return The modified string.
     */
    private static String reverse(String string)
    {
        String result = "";

        for (int i = string.length() - 1; i >= 0; i --)
            result += string.charAt(i);

        return result;
    }
}
